
$(function () {

    let pageNumber = $('.page-number').val();   //一开始默认的条数

    let classOnoff = false;    //用于记录班级数据开关

    let c_s_imformation;   //将学生信息和班级信息合并在一起,形成一个新的数据库

    let add_student = 0;     //当学生人数增加时，班级人数也要跟着增加


    //新的数据库
    function mergeStudentClass() {
        c_s_imformation = student_data;

        for(let i = 0; i < student_data.length; i++){
            for(let j = 0; j < class_data.length; j++){
                if(student_data[i].student_teacher === class_data[j].class_teacher){
                    //以主班老师为主键，连接学生信息和班级信息
                    c_s_imformation[i].student_assistant = class_data[j].class_assistant;
                    c_s_imformation[i].class_type = class_data[j].class_type;
                    c_s_imformation[i].class_name = class_data[j].class_name;
                    break;

                }
            }

        }
    }
    mergeStudentClass();





    //渲染数据到页面上
    for(let i = 0; i < pageNumber; i++){
        showData(i);
    }


    //搜索功能实现
    $('.search').click(function () {
        $('.student-data').html('');
        for(let i = 0; i < c_s_imformation.length; i++){
            let idVal = $('#student-id').val().trim();     //用户输入的学生学号
            let studentVal = $('#student-name').val().trim();   //用户输入学生名字
            let regId = new RegExp( idVal );     //匹配学生学号关键字
            let regStudent = new RegExp( studentVal );     //匹配学生名字关键字
            let sId = c_s_imformation[i].student_id;
            let sName = c_s_imformation[i].student_name;





            if(idVal && studentVal){
                //在学生学号、学生名字中都含有关键字
                if(sId.match(regId) && sName.match(regStudent)){
                    //学生学号、学生名字都能匹配成功

                    showData(i);
                    console.log(1);
                    classOnoff = true;
                }else {
                    if(!classOnoff && i === c_s_imformation.length-1){
                        alert('匹配条件失败，请重新输入');
                        return;
                    }
                }
            }else if(idVal){
                //在学生学号含有关键字,学生名字中未填写
                if(sId.match(regId)){
                    //学生学号匹配成功
                    showData(i);
                    classOnoff = true;
                }else {
                    if(!classOnoff && i === c_s_imformation.length-1){
                        alert('匹配条件失败，请重新输入');
                        return;
                    }
                }

            }else if(studentVal){
                //在学生名字含有关键字,学生学号中未填写
                if(sName.match(regStudent)){
                    //学生名字匹配成功
                    showData(i);
                    classOnoff = true;
                }else {
                    if(!classOnoff && i === c_s_imformation.length-1){
                        alert('匹配条件失败，请重新输入');
                        return;
                    }
                }
            }else{
                showData(i);
                if(i === c_s_imformation.length-1){
                    alert('未检测到您输入值，请输入匹配条件');
                    return;
                }


            }


        }
    })





    //td标签展现函数
    function showData(i) {
        
        let aTr = $('<tr></tr>');

        aTr.html(`<td class="serial-number">${i}</td>
                <td  class="sname">${c_s_imformation[i].student_name}</td>
                <td class="sid">${c_s_imformation[i].student_id}</td>
                <td class="steacher">${c_s_imformation[i].student_teacher}</td>
                <td class="ssex">${c_s_imformation[i].student_sex}</td>
                <td class="stel">${c_s_imformation[i].parent_tel}</td>
                <td class="sclass">${c_s_imformation[i].class_name}</td>
                <td class="stype">${c_s_imformation[i].class_type}</td>
                <td class="operate-data">
                    <button class="student-view" data-target="#studentView" data-toggle="modal">查看</button>
                    <button class="student-compile" data-target="#studentCompile" data-toggle="modal">编辑</button>
                    <button class="student-remove" data-target="#studentRemove" data-toggle="modal">删除</button>
                    
                </td>
                `)

        $('.student-data').append(aTr);
    }

    
    
    
    //点击新增学生显示表单
    $('.new-student-btn').click(function () {
        //在之前主班老师数据清空，之后重新显示
        $('.chooseMainTeacher').html('');
        //清空用户之前创建过的数据
        $('.openStudentName').val('');
        $('.openParentTel').val('');
        $('.openStudentNativePlace').val('');
        $('.openStudentIdNumber').val('');
        $('.openParentWeixin').val('');
        $('.openStudentAddress').val('');
        //调用函数，显示数据
        createNewStudent('.chooseMainTeacher');



    })



    //验证用户新增学生的表单数据
    $('.confirm').click(function () {


        if($('.openStudentName').val() && $('.chooseMainTeacher').val() && $('.chooseStudentSex').val() && $('.openParentTel').val() && $('.openStudentNativePlace').val() && $('.openStudentIdNumber').val() && $('.openParentWeixin').val() && $('.openStudentAddress').val()){
            let myRegTel = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
            let myRegId = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;



            if(myRegTel.test($('.openParentTel').val()) && myRegId.test($('.openStudentIdNumber').val())){

                //校验成功
                $('.student-data').html('');
                //当用户必填项都填写完整时，将新增的班级添加到数据库中
                student_data.push({
                    student_id: parseInt(student_data[student_data.length-1].student_id)+1,
                    student_name: $('.openStudentName').val(),
                    student_teacher: $('.chooseMainTeacher').val(),
                    student_sex: $('.chooseStudentSex').val(),
                    student_native_place: $('.openStudentNativePlace').val(),
                    student_id_number: $('.openStudentIdNumber').val(),
                    parent_weixin: $('.openParentWeixin').val(),
                    parent_tel : $('.openParentTel').val(),
                    address : $('.openStudentAddress').val()
                })

                //渲染数据到页面上

                mergeStudentClass();

                for(let i = 0; i < c_s_imformation.length; i++){
                    showData(i);
                }

                //新增引发总数据条数发生改变
                $('.total-number span').html(student_data.length);


                let data = {
                    teacherName : $('.chooseMainTeacher').val(),
                    classNumber : ++add_student
                }
                localStorage.removeItem("numberAdd");
                localStorage.setItem('numberAdd', JSON.stringify(data));

            }else{
                alert('电话号码或身份证号码不合法，请重新输入');
            }





        }else{
            //当用户必填项有任意一项未填
            alert('创建失败，必填项未输入未完整，请重新创建')

        }


    })



    //封装主班老师
    function createNewStudent(t) {
        let mainTeacher = [];    //用于装所有正在带班的主班老师
        let teacherOption = '';    //

        for(let i = 0; i < class_data.length; i++){
            //当主班老师的学生人数小于30时才可以进入新的同学
            if(class_data[i].class_number < 30){
                mainTeacher.push(class_data[i].class_teacher);
            }

        }

        for(let i = 0; i < mainTeacher.length; i++){
            if(i === 0){
                teacherOption += `<option selected>${mainTeacher[i]}</option>`
            }else {
                teacherOption += `<option>${mainTeacher[i]}</option>`
            }
        }

        $(t).html(teacherOption);



    }




    //删除数据
    $('body').on('click','.student-remove',function () {
        let _this = $(this);

        //不解绑的话会一直累计点击事件
        $('.confirm-remove').off('click').on('click',function(){

            $(_this).parent().parent().remove();
            let mainTeacher =_this.parent().parent().children('.steacher').html();
            console.log(mainTeacher);
            for(let i = 0; i < student_data.length; i++){
                if(student_data[i].student_teacher === mainTeacher){
                    student_data.splice(i,1);
                    i--;
                }
            }

            //删除引发总数据条数发生改变
            $('.total-number span').html(student_data.length);

            mergeStudentClass();


        })


    })





    //编辑功能实现
    $('body').on('click','.student-compile',function () {
        let _this = $(this);


        createNewStudent('.student_teacher');


        //找到可识别学生唯一值id号，以id号来遍历数据，从而展示到弹框上
        let sId = $(this).parent().parent().children('.sid').html();


        student_data.forEach(function (ele, index) {
            if(ele.student_id == sId){

                console.log(2);

                //将一开始的数据显示在弹窗上，供用户查看
                $('.student_name').val(ele.student_name);
                $('.student_teacher').val(ele.student_teacher);
                $('.student_sex').val(ele.student_sex);
                $('.student_native_place').val(ele.student_native_place);
                $('.student_id_number').val(ele.student_id_number);
                $('.parent_weixin').val(ele.parent_weixin);
                $('.parent_tel').val(ele.parent_tel);
                $('.address').val(ele.address);


                //用户修改数据后后台数据需要更新且展示的数据也需要更新
                $('.sure-modify').off('click').on('click',function () {


                    ele.student_name = $('.student_name').val();
                    ele.student_teacher = $('.student_teacher').val();
                    ele.student_sex = $('.student_sex').val();
                    ele.student_native_place = $('.student_native_place').val();
                    ele.parent_weixin = $('.parent_weixin').val();
                    ele.parent_tel = $('.parent_tel').val();
                    ele.address = $('.address').val();

                    //将新数据库也进行更改一下
                    mergeStudentClass();




                    _this.parent().parent().children('.sname').html( $('.student_name').val() );
                    _this.parent().parent().children('.steacher').html( $('.student_teacher').val() );
                    _this.parent().parent().children('.ssex').html( $('.student_sex').val() );
                    _this.parent().parent().children('.stel').html( $('.parent_tel').val() );

                    for(let j = 0; j < c_s_imformation.length; j++){
                        if(c_s_imformation[j].student_teacher === $('.student_teacher').val()){
                            _this.parent().parent().children('.sclass').html( c_s_imformation[j].class_name );
                            _this.parent().parent().children('.stype').html( c_s_imformation[j].class_type );
                        }
                    }

                })

            }

        })


    })


    //查看功能实现
    $('body').on('click','.student-view',function () {
        let _value = $(this).parent().parent().children('.sid').html();
        console.log(_value);

        for(let i = 0; i < c_s_imformation.length; i++){
            if(c_s_imformation[i].student_id === _value){

                $('.view-id').val(c_s_imformation[i].student_id);
                $('.view_name').val(c_s_imformation[i].student_name);
                $('.view_teacher').val(c_s_imformation[i].student_teacher);
                $('.view_assister').val(c_s_imformation[i].student_assistant);
                $('.view_class_name').val(c_s_imformation[i].class_name);
                $('.view_class_type').val(c_s_imformation[i].class_type);
                $('.view_sex').val(c_s_imformation[i].student_sex);
                $('.view_tel').val(c_s_imformation[i].parent_tel);
                $('.view_native_place').val(c_s_imformation[i].student_native_place);
                $('.view_id_number').val(c_s_imformation[i].student_id_number);
                $('.view_weixin').val(c_s_imformation[i].parent_weixin);
                $('.view-address').val(c_s_imformation[i].address);
            }
        }
    })



    //分页功能实现
    $(function(){
        let lastIndex = 0;  //上一页下一页，第几页的实现
        let sNumber = 0;        //具体页数

        //页面一加载就显示具体的条数
        $('.total-number span').html(class_data.length);


        //当用户选择的显示条数发生改变时
        $('.page-number').on('change',function () {
            pageNumber = $('.page-number').val();   //获取用户选择的条数
            $('.student-data').html('');     //将之前的数据清空


            lastIndex = 0;     //上一页下一页，第几页的实现
            PageNumber();

            //更改页面展示条数
            for(let i = 0; i < Math.min(pageNumber, student_data.length); i++){
                showData(i);
            }

        })


        //封装根据用户选择的条数情况显示应该分多少页
        function PageNumber() {
            //根据用户选择的条数情况显示应该分多少页
            sNumber = Math.floor( student_data.length / pageNumber ) + 1;

            let aUl = ''
            for(let i = 0; i < sNumber; i++){
                if(i === 0){
                    aUl += `<li class="active pn"><a href="#">${i+1}</a></li>`
                }else{
                    aUl += `<li class="pn"><a href="#">${i+1}</a></li>`
                }

            }
            $('.choose-number').html(aUl);
        }
        PageNumber()



        //用户点击改变页数时
        $('body').on('click','.pn', function () {

            changePageNumber($(this).index())
        })

        //用户点击调到上一页
        $('body').on('click','.previous',function () {
            let index = lastIndex - 1;
            if( index <= 0 ){
                index = 0;
            }
            changePageNumber(index);
        })

        //用户点击调到下一页
        $('body').on('click','.next',function () {
            let index = lastIndex + 1;
            if( index >= sNumber-1 ){
                index = sNumber-1;
            }
            changePageNumber(index);
        })

        //用户输入数字直接调到某页
        $('body').on('change','.leave-for',function () {
            let index = $('.leave-for').val()-1;
            if(index >= sNumber-1){
                index = sNumber-1;
            }
            if(index <= 0){
                index = 0;
            }
            changePageNumber(index);
        })




        //封装页数改变函数
        function changePageNumber(index) {
            $('.student-data').html('');     //将之前的数据清空
            //将上一个选中样式去掉，新的添加上选中样式
            $('.choose-number li').eq(lastIndex).removeClass('active');
            $('.choose-number li').eq(index).addClass('active');



            for(let i = index*pageNumber; i < Math.min((index+1)*pageNumber, student_data.length); i++){
                showData(i);
            }
            lastIndex = index;

            console.log(pageNumber);
        }



    })



})